package org.example.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.*;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

@Slf4j
public class KafkaConsumerExample {

    public static void main(String[] args) {
        // 配置消费者属性
        Properties properties = new Properties();
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.236.128:9092");  // Kafka Broker 地址
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");  // 消费者组ID
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // 键反序列化
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // 值反序列化
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // 自动重置消费偏移量的策略（latest/earliest）

        // 创建 KafkaConsumer 实例
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

        // 订阅主题
        consumer.subscribe(Collections.singletonList("test4"));

        // 消费消息
        try {
            while (true) {
                // 拉取消息
                ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));// 每次最多阻塞 1 秒钟
                for (ConsumerRecord<String, String> record : records) {
                    log.info("Consumed record: key={},value={}, from partition {}", record.key(), record.value(), record.partition());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            consumer.close();  // 关闭消费者
        }
    }
}
